<?php
/*
* Author：鑫宇工作室
* QQ：639519801
* url：www.xinyuream.com
*/
include_once $_SERVER['DOCUMENT_ROOT'].'/func/include.php';
$captcha = new Captcha(120,38,4);
$code = $captcha->render();
$_SESSION['code'] = $code;
  class Captcha {
      protected $width; //画布宽度
      protected $height; //画布高度
      protected $res; //画布
      protected $len;//验证码长度
      protected $code; //验证码
      public function __construct($width = 100,$height = 30,$len = 4) {
          $this->width = $width;
          $this->height = $height;
          $this->len = $len;
      }
      public function render() {
          $res = imagecreatetruecolor($this->width,$this->height);
          imagefill($this->res=$res,0,0,imagecolorallocate($res,200,200,200));
          $this->text();
          $this->line();
          $this->pix();
          $this->show();
          return $this->code;
      }
      protected function show() {
        header('Content-type:image/png');
        imagepng($this->res);
      }
      //生成随机码
      protected function text() {
          $font = realpath('./font/2.ttf');
          $text = 'abcdefghijklmnopqrstuvwxyz123456789';
          for($i=0;$i<$this->len;$i++) {
              $x = $this->width / $this->len;
              $angle = mt_rand(-20,20);
              $box = imagettfbbox(20,$angle,$font,'A');
              $this->code .= $code = strtoupper($text[mt_rand(0,strlen($text)-1)]);
              imagettftext(
                  $this->res,
                  20,
                  mt_rand(-20,20),
                  $x*$i +10,
                  $this->height / 2 - ($box[7] - $box[0]) /2,
                  $this->textColor(),
                  $font,
                  $code
              );
          };
      }
      //生成随机颜色的干扰线
      protected function line() {
        for($i=0;$i<3;$i++) {
            imageline(
                $this->res,
                mt_rand(0,$this->width),
                mt_rand(0,$this->height),
                mt_rand(0,$this->width),
                mt_rand(0,$this->height),
                $this->color()
            );
        }
      }
      //生成随机颜色
      protected function color() {
          return imagecolorallocate($this->res,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
      }
      protected function textColor() {
        return imagecolorallocate($this->res,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
      }
      //绘制干扰点
      protected function pix() {
          for($i=0;$i<100;$i++) {
              imagesetpixel($this->res,mt_rand(0,$this->width),mt_rand(0,$this->height),$this->color());
          }
      }
  }
?>